package server;


import java.io.File;
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.IOException;  

import org.apache.catalina.LifecycleException;  
import org.apache.catalina.core.AprLifecycleListener;  
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardServer;  
import org.apache.catalina.startup.ClassLoaderFactory;  
import org.apache.catalina.startup.ContextConfig;
import org.apache.catalina.startup.Tomcat;  

import javax.servlet.ServletException;  

import org.xml.sax.SAXException;  


public class QuickStartByTomcat {
	
	String pathToGlobalWebXml = "./conf/web.xml";
	
	private Tomcat tomcat;  
    private void startTomcat(int port,String contextPath,String baseDir) throws ServletException, LifecycleException {  
        tomcat = new Tomcat();  
        tomcat.setPort(port);  
        tomcat.setBaseDir(".");  
        
        StandardServer server = (StandardServer) tomcat.getServer();  
        AprLifecycleListener listener = new AprLifecycleListener();  
        server.addLifecycleListener(listener);  
        
        StandardContext context = new StandardContext();
        context.setName(baseDir);
        context.setPath(contextPath);
        context.setDocBase(baseDir);
        context.setRealm(tomcat.getHost().getRealm());
        
        ContextConfig contextConfig = new ContextConfig();
        if (new File(pathToGlobalWebXml).exists()) {
            contextConfig.setDefaultWebXml(pathToGlobalWebXml);
        } 
        context.addLifecycleListener(contextConfig);
        tomcat.getHost().addChild(context);
       
        //-tomcat.addWebapp(contextPath, baseDir);  
        tomcat.start();  
    }  
    private void stopTomcat() throws LifecycleException {  
        tomcat.stop();  
    }  
    
    public static void main(String[] args) {  
    	int port = 9000;  
        String contextPath = "";  
        String baseDir = "../WebRoot";  
         
        try {  
        	if(args.length>=2){
        		baseDir = args[1];
        	}
        	if(args.length>=1){
        		port = Integer.valueOf(args[0]);
        	}
        	else{
        		System.out.println("usage: [port] [webapp-path]");
        	}
           
            QuickStartByTomcat tomcat = new QuickStartByTomcat();  
            tomcat.startTomcat(port, contextPath, baseDir);           
            
            //由于Tomcat的start方法为非阻塞方法,加一个线程睡眠模拟线程阻塞.  
            tomcat.tomcat.getServer().await();
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
}
